﻿using GalaSoft.MvvmLight.Command;
using GalaSoft.MvvmLight.Messaging;
using Medecine.DataAccess.Users;
using Medecine.Interface.Main;
using Medecine.Interface.Properties;
using System.Reactive.Linq;
using Medecine.Dbo;
using System;

namespace Medecine.Interface.Login
{
	public class LoginViewModel : ViewModelWithErrors
	{
		public LoginViewModel()
		{
			_loginCommand = new RelayCommand(Login, CanLogin);
			Messenger.Default.Register<PasswordChangedMessage>(this, (m) => _loginModel.Password = m.Content);
		}

		private readonly LoginModel _loginModel = new LoginModel();

		public string UserName
		{
			get { return _loginModel.UserName; }
			set
			{
				if (_loginModel.UserName == value)
					return;
				_loginModel.UserName = value;
				RaisePropertyChanged("UserName");
			}
		}

		#region Command

		private readonly RelayCommand _loginCommand = null;
		public RelayCommand LoginCommand { get { return _loginCommand; } }

		private bool CanLogin()
		{
			return (string.IsNullOrEmpty(UserName) == false)
				&& (string.IsNullOrEmpty(_loginModel.Password) == false);
		}

		private void Login()
		{
			using (ServiceUserClient service = new ServiceUserClient())
			{
				Observable.FromAsyncPattern<string, string, bool>(service.BeginConnect, service.EndConnect)
					.Invoke(UserName, _loginModel.Password)
					.ObserveOnDispatcher()
					.Subscribe(LoginCompleted, (e) => Messenger.Default.Send(new ErrorMessage(e.Message)));
			}
		}

		private void LoginCompleted(bool result)
		{
			if (result == false)
				Messenger.Default.Send(new ErrorMessage(Resources.LoginError));
			else
				GetUser();
		}

		private void GetUser()
		{
			using (ServiceUserClient service = new ServiceUserClient())
			{
				Observable.FromAsyncPattern<string, User>(service.BeginGetUser, service.EndGetUser)
					.Invoke(UserName)
					.ObserveOnDispatcher()
					.Subscribe(GetUserCompleted, (e) => Messenger.Default.Send(new ErrorMessage(e.Message)));
			}
		}

		private void GetUserCompleted(User user)
		{
			Messenger.Default.Send(new LoginMessage(user));
		}

		#endregion // Command
	}
}